package com.shop.resource.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.shop.resource.service.IFileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Description:
 *
 * @author zhoulk
 * @date: 2019年05月08日  13:42
 */
@Service
public class FileService implements IFileService {

    @Value("${qiniu.accessKey}")
    private String accessKey;
    @Value("${qiniu.secretKey}")
    private String secretKey;
    @Value("${qiniu.bucket}")
    private String bucket;
    @Value("${qiniu.resurl}")
    private String resurl;

    @Override
    public Map<String, Object> uploadImgToQi(MultipartFile file) {
        Configuration cfg = new Configuration(Zone.zone0());
        UploadManager uploadManager = new UploadManager(cfg);
        String key= UUID.randomUUID().toString()+".jpg";
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        String name="";
        try {
            Response response =   uploadManager.put(file.getBytes(),key,upToken);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            name=putRet.key;
        } catch (IOException e) {
            e.printStackTrace();
        }
        String[] values = { resurl+name };
        Map<String,Object> map = new HashMap<>();
        map.put("errno",0);
        map.put("data",values);
        return map;
    }

    @Override
    public String getUploadToken() {
        String key= UUID.randomUUID().toString()+".jpg";
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        Map<String, String> result = new HashMap<>();
        result.put("key", key);
        result.put("token", upToken);
        return JSON.toJSONString(result);
    }
}
